package com.iskyline.demo.tools.photo;

import com.iskyline.demo.tools.photo.exceptions.PhotoException;
import com.iskyline.demo.tools.photo.service.PhotoService;
import com.iskyline.utils.FileUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 相册整理启动类
 * @Author:      iskyline
 * @JDK:         1.8
 * @Date:        2019/8/10 17:17
 */
@Service
public class PhotoBoot {
    private final static Logger LOGGER = LoggerFactory.getLogger(PhotoBoot.class);

    @Autowired
    private PhotoApplicationProperties photoApplicationProperties;
    @Autowired
    private PhotoService photoService;

    public void boot() throws PhotoException {
        File rootFolder = this.getRootFolder();
        LOGGER.info("==>PhotoBoot#boot:::rootFolder={}",rootFolder.toString());

        List<File> allFileList = new ArrayList<>();
        this.recursiveFiles(rootFolder,allFileList);

        LOGGER.info("==>PhotoBoot#boot:::allFileList={}",allFileList.size());

        /*for (File file : allFileList) {
            System.out.println(file);
        }*/

    }

    private void recursiveFiles(File file,List<File> allFileList){
        if(FileUtils.isEmpty(file)){
            return;
        }
        if(file.isFile()){
            allFileList.add(file);
            return;
        }
        List<File> fileList = FileUtils.scanFiles(file);
        allFileList.addAll(fileList);
        List<File> folderList = FileUtils.scanFolder(file);
        if(CollectionUtils.isEmpty(folderList)){
            return;
        }
        for (File folder : folderList) {
            recursiveFiles(folder,allFileList);
        }
    }

    private File getRootFolder() throws PhotoException{
        String folderPath = photoApplicationProperties.getFolder();
        if(StringUtils.isBlank(folderPath)){
            throw new PhotoException("获取不到相册根目录");
        }
        File rootFile = new File(folderPath);
        if(!rootFile.isDirectory()){
            throw new PhotoException("路径不是文件夹:"+folderPath);
        }
        if(!rootFile.exists()){
            throw new PhotoException("文件夹不存在:"+folderPath);
        }
        return rootFile;
    }

}
